package com.example.rabbitmq;

import com.example.Configuration;
import com.example.order.OrderHandler;
import com.rabbitmq.client.*;
import com.sun.org.apache.xpath.internal.operations.Or;

import java.io.IOException;

/**
 * 接收服务端发送过来的订单信息
 * 将订单信息载入订单队列中 并将文件提交到文件下载队列
 */
public class ReceiveServerMessage {
    /**
     * 接收交换机所绑定的队列消息 获取订单编号
     * 将订单编号提交到订单处理程序 从服务端获取订单信息
     * 消息接收模式设置为手动回复机制
     * @param queueName
     * @throws Exception
     */
    public static void receiveMessageExchange(String queueName)throws Exception{
        //设置queueName的值为所绑定的交换机的queue的值
        //String queueName  = "ba7755d1-f0c1-4cfa-8553-749671a6c151";
        Connection connection = RabbitMQConnection.getConnection();
        Channel channel = RabbitMQConnection.getChannel(connection);
        //设置自动回复为false当接收到消息后在返回确认消息报文
        boolean autoAck = false;
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        channel.basicConsume(queueName,autoAck,"myConsumerTag",new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[]  body) throws IOException {
                long deliveryTag = envelope.getDeliveryTag();
                //获取到的消息为订单ID 这里可以使用多线程并发机制去后台请求订单数据
                //也可以设计为提交到RabbitMQ的消息队列中 设置多线程池去消费其中的订单信息
                String message = new String(body,"UTF-8");
                System.out.println("收到订单号:"+message);
                if(message == null || message.equals("")){
                    System.out.println("消息错误!");
                    return;
                }
                //将orderId推送到订单处理流程
                OrderHandler orderHandler = new OrderHandler();
                orderHandler.getOrderInfo(message);
                //回复确认消息
                channel.basicAck(deliveryTag, false);
            }
        });
    }
}
